<template>
  <div class="app-container">
    <!-- 表单部分 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <!-- 各个表单项 -->
      <el-form-item label="库存编号" prop="inventoryId">
        <el-input
          v-model="queryParams.search.inventoryId"
          placeholder="请输入库存编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="productId">
        <el-input
          v-model="queryParams.search.productId"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="包装类型" prop="packageType">
        <el-input
          v-model="queryParams.search.packageType"
          placeholder="请输入包装类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDeleteAll"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格展示 -->
    <el-table
      v-loading="loading"
      :data="inventoryList"
      @selection-change="handleSelectionChange"
      type="selection"
      show-row-hover
      selection-mode="multiple"
      header-cell-class-name="custom-checkbox-header"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="50"></el-table-column>
      <!-- 各列定义 -->
      <el-table-column prop="inventoryId" label="库存编号"></el-table-column>
      <el-table-column prop="productId" label="商品编号"></el-table-column>
      <el-table-column
        prop="product.productName"
        label="商品名称"
      ></el-table-column>
      <el-table-column prop="product.brand" label="品牌"></el-table-column>
      <el-table-column
        prop="product.description"
        label="描述"
      ></el-table-column>
      <el-table-column prop="packageType" label="包装类型"></el-table-column>
      <el-table-column
        prop="unitPurchasePrice"
        label="进货单价"
      ></el-table-column>
      <el-table-column label="库存数量">
        <template #default="scope">
          <span :class="scope.row.inventoryQuantity <= 10? 'low-stock' : ''">
            {{ scope.row.inventoryQuantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="库存告急" placement="top">
            <el-button
              type="text"
              icon="Plus"
              @click="showStockAlert(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              type="text"
              icon="Edit"
              @click="handleUpdateRow(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        class="pagiantion"
        @current-change="handleCurrentChange"
        :current-page="queryParams.page"
        :page-size="queryParams.count"
        layout="total, prev, pager, next, jumper"
        :total="queryParams.total"
      >
      </el-pagination>
    </div>

    <!-- 添加或修改出库单对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body v-if="open">
      <el-form
        ref="inventoryRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 表单行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存编号" prop="inventoryId">
              <el-input
                v-model="form.inventoryId"
                placeholder="请输入库存编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品编号" prop="productId">
              <el-input v-model="form.productId" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="包装类型" prop="packageType">
              <el-input
                v-model="form.packageType"
                placeholder="请输入包装类型"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进货单价" prop="unitPurchasePrice">
              <el-input
                v-model="form.unitPurchasePrice"
                placeholder="请输入进货单价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存数量" prop="inventoryQuantity">
              <el-input
                v-model="form.inventoryQuantity"
                placeholder="请输入库存数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm('inventoryRef')"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库存告急弹出框 -->
    <el-dialog title="添加库存申请" v-model="stockAlertDialogVisible">
      <el-form
        ref="stockAlertForm"
        :model="stockAlertFormData"
        :rules="stockAlertRules"
      >
        <!-- 表单行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编号" prop="productId">
              <el-input
                v-model="stockAlertFormData.productId"
                placeholder="请输入商品编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-model="stockAlertFormData.productName"
                placeholder="请输入产品名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input
                v-model="stockAlertFormData.brand"
                placeholder="请输入品牌"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品数量" prop="salesDetNum">
              <el-input
                v-model="stockAlertFormData.salesDetNum"
                placeholder="请输入商品数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注" prop="note">
              <el-input
                v-model="stockAlertFormData.note"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStockAlert">确定</el-button>
          <el-button @click="stockAlertDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Inventory">
import {
  addInventory,
  addInventoryApproval,
  delInventory,
  listInventory,
  updateInventory,
} from "@/api/sale/salesinventory";
import { getCurrentInstance, reactive, ref } from "vue";

const { proxy } = getCurrentInstance();
const inventoryList = ref([]);
const outboundDetailList = ref([]);
const open = ref(false);
const openTwo = ref(false);
const openThird = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const titleTwo = ref("");
const titleThird = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const stockAlertDialogVisible = ref(false);

// 添加一个响应式变量来存储选中的库存单记录
const selectedInventoryIds = reactive([]);

const data = reactive({
  form: {
    inventoryId: null,
    productId: null,
    packageType: null,
    unitPurchasePrice: null,
    inventoryQuantity: null,
    outboundEntryId: null,
    productName: null,
    brand: null,
    description: null,
  },
  queryParams: {
    page: 1,
    total: 10,
    count: 5,
    search: {
      inventoryId: undefined,
      productId: undefined,
      packageType: undefined,
    },
  },
  rules: {
    inventoryId: [
      { required: true, message: "库存编号不能为空", trigger: "blur" },
    ],
    productId: [
      { required: true, message: "商品编号不能为空", trigger: "blur" },
    ],
    packageType: [
      { required: true, message: "包装类型不能为空", trigger: "blur" },
    ],
    unitPurchasePrice: [
      { required: true, message: "进货单价不能为空", trigger: "blur" },
    ],
    inventoryQuantity: [
      { required: true, message: "库存数量不能为空", trigger: "blur" },
    ],
    salesDetNum: [
      { required: true, message: "商品数量不能为空", trigger: "blur" },
    ],
    note: [{ required: true, message: "备注不能为空", trigger: "blur" }],
    brand: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" },
    ],
  },
  stockAlertFormData: {
    orderId: null,
    productId: null,
    productName: null,
    brand: null,
    salesDetNum: null,
    note: null,
  },
});

const { queryParams, form, rules } = toRefs(data);

const stockAlertFormData = reactive({
  orderId: null,
  productId: null,
  productName: null,
  brand: null,
  salesDetNum: null,
  note: null,
});

// 查询库存列表
function getList() {
  loading.value = true;
  listInventory(queryParams.value)
    .then((response) => {
      inventoryList.value = response.data.list;
      queryParams.value.page = response.data.current;
      queryParams.value.total = response.data.total;
      loading.value = false;
    })
    .catch(() => {
      // 请求失败时将 queryParams.page 传上去重新请求
      queryParams.value.page = queryParams.page;
    });
}

// 切换页码
function handleCurrentChange(currentPage) {
  queryParams.value.page = currentPage;
  getList();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function cancelThird() {
  openThird.value = false;
  queryParams.value.page = 1;
}

function cancelTwo() {
  openTwo.value = false;
}

// 表单重置
function reset() {
  form.value = {
    inventoryId: null,
    productId: null,
    packageType: null,
    unitPurchasePrice: null,
    inventoryQuantity: null,
    outboundEntryId: null,
  };
  proxy.resetForm("inventoryRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.page = queryParams.value.page || 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.search.inventoryId = undefined;
  queryParams.value.search.productId = undefined;
  queryParams.value.search.packageType = undefined;
  handleQuery();
}

// 新增库存按钮操作
function handleAdd() {
  reset();
  data.form.isNew = true;
  open.value = true;
  title.value = "添加库存";
}

// 删除单个按钮操作
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.inventoryId + '"的数据项?')
    .then(function () {
      return delInventory(row.inventoryId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 更新选中记录数组
      selectedInventoryIds.splice(selectedInventoryIds.indexOf(row), 1);
    })
    .catch(() => {});
}

// 删除多个按钮操作
function handleDeleteAll() {
  const idsToDelete = selectedInventoryIds.map((item) => item.inventoryId);
  if (idsToDelete.length === 0) {
    proxy.$modal.msgWarning("请先选择要删除的库存单");
    return;
  }
  proxy.$modal
    .confirm("是否确认删除选中的 " + idsToDelete.length + " 个库存单数据项?")
    .then(function () {
      return Promise.all(idsToDelete.map((id) => delInventory(id)));
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 清空选中记录数组
      selectedInventoryIds.length = 0;
    })
    .catch(() => {});
}

// 添加或修改按钮操作
function submitForm(formName) {
  if (formName === "inventoryRef") {
    // 提交或修改库存表单
    proxy.$refs.inventoryRef.validate((valid) => {
      if (valid) {
        if (data.form.isNew) {
          // 新增库存逻辑
          addInventory(data.form)
            .then(() => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.error("新增失败：", error);
              proxy.$modal.msgError("新增失败：" + error.message);
            });
        } else {
          // 修改库存逻辑
          updateInventory(data.form)
            .then(() => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              handleQuery();
            })
            .catch((error) => {
              console.error("修改失败：", error);
              proxy.$modal.msgError("修改失败：" + error.message);
            });
        }
      } else {
        console.error("表单验证不通过，请检查输入内容");
        proxy.$modal.msgError("表单验证不通过，请检查输入内容");
      }
    });
  }
}

// 修改单个行的操作
function handleUpdateRow(row) {
  // 将选中行的数据复制到表单中进行编辑
  form.value = { ...row };
  open.value = true;
  title.value = "修改库存";
}

// 显示库存告急弹出框
function showStockAlert(row) {
  stockAlertFormData.productId = row.productId;
  stockAlertFormData.productName = row.product.productName;
  stockAlertFormData.brand = row.product.brand;
  stockAlertDialogVisible.value = true;
}

// 提交库存告急申请
function submitStockAlert() {
  // 进行表单验证
  proxy.$refs.stockAlertForm.validate((valid) => {
    if (valid) {
      // 发送添加库存审批请求
      addInventoryApproval(stockAlertFormData)
        .then(() => {
          proxy.$modal.msgSuccess("库存申请提交成功");
          stockAlertDialogVisible.value = false;
        })
        .catch((error) => {
          console.error("库存申请提交失败：", error);
          proxy.$modal.msgError("库存申请提交失败：" + error.message);
        });
    } else {
      console.error("表单数据为空，请检查");
      proxy.$modal.msgError("表单数据为空，请检查");
    }
  });
}

// 表格选中项变化处理函数（包括复选框和行选择）
function handleSelectionChange(selection) {
  selectedInventoryIds.length = 0;
  selectedInventoryIds.push(...selection);
}

// 全选复选框变化处理函数
function handleCheckboxAllChange(val) {
  inventoryList.value.forEach((row) => {
    row.$selected = val;
  });
  if (val) {
    // 如果全选，将所有行添加到选中记录数组
    selectedInventoryIds.length = 0;
    selectedInventoryIds.push(...inventoryList.value);
  } else {
    // 如果取消全选，清空选中记录数组
    selectedInventoryIds.length = 0;
  }
}

getList();
</script>

<style>
/* 自定义表头复选框样式（可选） */
.custom-checkbox-header.el-checkbox__input.is-checked +.el-checkbox__label {
  color: #409eff; /* 选中时字体颜色 */
}

.custom-checkbox-header.el-checkbox__input.is-indeterminate +.el-checkbox__label {
  color: #409eff; /* 半选时字体颜色 */
}

.low-stock {
  color: red;
}
</style>
